/**
 * Copyright (c) 2011, Jason Gardner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.freecake.bonejams.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

import org.freecake.bonejams.model.Album;
import org.freecake.bonejams.model.Mp3File;

import java.io.File;
import java.util.ArrayList;
import java.util.Vector;

public class Database {

    SQLiteDatabase database = null;
    final String dbTable = "MP3Files";
    
    public Database(String name, int version) {
        File dbFile = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dbFile = new File(Environment.getExternalStorageDirectory(), name + ".sqlite");
        } else {
            Log.e(getClass().getName(), "Unable to load database.  SDCard not mounted.");
            return;
        }
        
        if (dbFile.exists()) {        
            database = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
            if (version != database.getVersion()) {
                upgrade(version);
            }
        } else {
            database = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
            create(version);
        }
    }
        
    public void close() {
        Log.i(getClass().getName(), "Closing database...");
        database.close();
    }

    public void create(int version) {
        try{
            Log.d(getClass().getName(), "Creating Database...");
            database.execSQL("CREATE TABLE [" + dbTable + "] ("+
                        "[file] TEXT  UNIQUE NOT NULL PRIMARY KEY,"+
                        "[title] TEXT  NULL,"+
                        "[artist] TEXT  NULL,"+
                        "[album] TEXT  NULL"+
                        ")");
            database.setVersion(version);
            Log.d(getClass().getName(), "Database created");
        } catch(SQLException e) {
            Log.e(getClass().getName(),"Could not create database", e);
        }
    }

    public void upgrade(int version) {
        Log.d(getClass().getName(), "Upgrading Database...");
        database.execSQL("DROP TABLE IF EXISTS " + dbTable);
        create(version);
    }
    
    public void clear() {
        Log.d(getClass().getName(), "Clearing Database...");
        try {
            database.delete(dbTable, null, null);
        } catch (Exception e) {
            Log.d(getClass().getName(), "Unable to clear database.", e);
        }
    	database.delete(dbTable, null, null);        
    }
    
    public void insertMP3File(String file, String title, String artist, String album) {
        ContentValues values = new ContentValues();
        values.put("file", file);
        values.put("title", title);
        values.put("artist", artist);
        values.put("album", album);   
        database.insertOrThrow(dbTable, null, values);
    }

    private Mp3File loadMp3File(Cursor cursor){
        Mp3File file = new Mp3File(cursor.getString(cursor.getColumnIndex("file")),
                                    cursor.getString(cursor.getColumnIndex("title")),
                                    cursor.getString(cursor.getColumnIndex("artist")),
                                    cursor.getString(cursor.getColumnIndex("album")));
        		
		return file;
    }
    
	public ArrayList<Mp3File> getAllSongs() {
    	Cursor cursor = database.query(dbTable, null, null, null, null, null, "title ASC");
    	cursor.moveToFirst();
    	ArrayList<Mp3File> songs = getSongsViaCursor(cursor);
    	cursor.close();
    	return songs;
	}
	
	public ArrayList<Album> getAllAlbums() {
    	Cursor cursor = database.query(dbTable, new String[] {"album","artist"},
                                        null, null, "album", null, "album ASC");
    	cursor.moveToFirst();
    	ArrayList<Album> albums = getAlbumsViaCursor(cursor);
    	cursor.close();
    	return albums;        
	}	
	
	public String[] getAllArtists() {
    	Cursor cursor = database.query(dbTable, new String[] {"artist"},
                                        null, null, "artist", null, "artist ASC");
    	cursor.moveToFirst();
    	Vector artists = new Vector();
    	while (!cursor.isAfterLast()){
    		artists.add(cursor.getString(cursor.getColumnIndex("artist")));
    		cursor.moveToNext();
    	}    	
    	cursor.close();
    	return (String[]) artists.toArray(new String[artists.size()]);       
	}
	
	public ArrayList<Mp3File> getSongsOnAlbum(String albumTitle, String albumArtist) {
    	Cursor cursor = database.query(dbTable, null,
                                       "artist=\"" + albumArtist + "\" AND album=\"" + albumTitle + "\"",
                                        null, null, null, "file ASC");
    	cursor.moveToFirst();
    	ArrayList<Mp3File> songs = getSongsViaCursor(cursor);
    	cursor.close();
    	return songs;	    
	}
	
	public ArrayList<Mp3File> getSongsByArtist(String artist) {
    	Cursor cursor = database.query(dbTable, null,
                                       "artist=\"" + artist + "\"",
                                       null, null, null, "file ASC");
    	cursor.moveToFirst();
    	ArrayList<Mp3File> songs = getSongsViaCursor(cursor);
    	cursor.close();
    	return songs;	
	}    
	
	public Mp3File getSongByFileName(String filePath) {
    	Cursor cursor = database.query(dbTable, null,
                                       "file=\"" + filePath + "\"",
                                       null, null, null, "file ASC");
    	cursor.moveToFirst();
    	ArrayList<Mp3File> songs = getSongsViaCursor(cursor);
    	cursor.close();
    	if (songs.size() == 0) {
    	    Log.i(getClass().getName(), "Couldnt find file '" + filePath + "'");    	    
    	}
    	return (songs.size() > 0) ? songs.get(0) : null;	
	}    	
	
    private ArrayList<Mp3File> getSongsViaCursor(Cursor cursor){
    	ArrayList<Mp3File> songs = new ArrayList<Mp3File>();
    	while (!cursor.isAfterLast()){
    		songs.add(loadMp3File(cursor));
    		cursor.moveToNext();
    	}
    	return songs;
    }

    private ArrayList<Album> getAlbumsViaCursor(Cursor cursor){
    	ArrayList<Album> albums = new ArrayList<Album>();
    	while (!cursor.isAfterLast()){
    	    Album album = new Album(cursor.getString(cursor.getColumnIndex("album")), 
    	                             cursor.getString(cursor.getColumnIndex("artist")));
    		albums.add(album);
    		cursor.moveToNext();
    	}
    	return albums;
    } 	

}
